package com.cby.android.olive.utils

import android.Manifest.permission
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import androidx.annotation.RequiresPermission


/**
 * 网络检测工具
 *
 * @author 陈宝阳
 * @create 2020/4/13 15: 57
 */
object NetworkUtils {

    /**
     * 判断是否有网络
     *
     * @param context
     * @return
     */
    @JvmStatic
    @RequiresPermission(permission.ACCESS_NETWORK_STATE)
    fun isConnected(context: Context): Boolean {
        val info = getActiveNetworkInfo(context.applicationContext)
        return info != null && info.isConnected
    }

    /**
     * 获取网络状态信息
     *
     * @param context
     * @return
     */
    @JvmStatic
    @RequiresPermission(permission.ACCESS_NETWORK_STATE)
    private fun getActiveNetworkInfo(context: Context): NetworkInfo? {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            ?: return null
        return cm.activeNetworkInfo
    }

    /**
     * 检查是否是Wi-Fi连接
     *
     *  @param context
     * @return
     */
    @RequiresPermission(permission.ACCESS_NETWORK_STATE)
    fun isWifiConnected(context: Context): Boolean {
        val cm =
            context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                ?: return false
        val ni = cm.activeNetworkInfo
        return ni != null && ni.type == ConnectivityManager.TYPE_WIFI
    }
}